#ifndef LS_StreamHandler_H
#define LS_StreamHandler_H

#include "common.h"
#include <queue>
#include "SyncQueue.hpp"
#include "WebsocketClient.h"
#include "Package.h"

class StreamHandler
{
private:
    // 接收数据的队列
    SyncQueue<Package> *m_buffer_queue;
    WebsocketClient *m_client;

    void startLoop() {
        for (;;)
        {
  
            if (m_buffer_queue->get_needStop()) break;
            auto package = m_buffer_queue->take();

            if (!package->isNull())
            {
                size_t count = package->count;
                std::cout << "send data to server: " << count << std::endl;
               // 发数据
                m_client->sendBinaryData(package->data, count);
                // free(package.data);
                // package.flush();
            }
        }
    }

public:

    enum TransportType {
        websocket
    };

    StreamHandler() {
        m_buffer_queue = new SyncQueue<Package>(50);
        m_client = new WebsocketClient();
        std::thread(&StreamHandler::startLoop, this).detach();
    };

    ~StreamHandler() {
        delete m_buffer_queue;
        delete m_client;
    };

    void set_receive_handler(WebsocketClient::receive_handler h) {
        m_client->set_receive_handler(h);
    }

    void open(TransportType type, std::string uri) {
        std::thread t(&WebsocketClient::open, m_client, uri);
        t.detach();
    }

    /// @note 必须使用一个单独的同步队列调用
    void append(Package &&package) {
        m_buffer_queue->put(package);
    }

    void close() {
        m_buffer_queue->stop();
        m_client->close();
    }

    bool get_connected() {
        return m_client->get_is_connect();
    }
};

#endif